package com.nwpu.controller;

import com.nwpu.common.ErrorEnum;
import com.nwpu.common.Result;
import com.nwpu.util.EmailUtil;
import com.nwpu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * key 邮箱号  value 验证码
 */
@RestController
@RequestMapping("/email")
public class MailController {
 
    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisUtil redisUtil;
 
    //发送邮箱验证码
    @GetMapping("send/{email}")
    public Result<String> sendE(@PathVariable String email) {
        //如果从redis获取不到，生成新的6位验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println("后台生成的--code--:"+code);
        //调用service方法，通过邮箱服务进行发送
        boolean res = emailUtil.sendMail(email, "邮箱验证码","验证码:"+code);
        //生成验证码放到redis里面，设置有效时间为5分钟
        if (res) {
            redisUtil.set(email, String.valueOf(code), 5);
            return Result.of((String) redisUtil.get(email));
        } else {
            return Result.error(ErrorEnum.INTERNAL_SERVER_ERROR);
        }
    }

    //验证邮箱验证码
    @GetMapping("verify/{email}/{code}")
    public Result<String> verify(@PathVariable String email,@PathVariable String code) {
        //从redis获取验证码
        String standCode = (String) redisUtil.get(email);
        if (standCode == null) {
            return Result.of("验证码已过期或者不存在");
        }
        if (code.equals(standCode)) {
            return Result.of("验证成功");
        } else {
            return Result.error(ErrorEnum.INTERNAL_SERVER_ERROR);
        }
    }
}
 